//
//  FeedBackViewController.m
//
//
//  Created by BiaomingZhong on 15-1-19.
//  Copyright (c) 2015年 BiaomingZhong. All rights reserved.
//

#import "FeedBackViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "AFNetworking.h"
#import "PromptInfoView.h"

#import "GCPlaceholderTextView.h"
#import "RequestNetWork.h"
#import "StartPageController.h"
#import "validateInputValue.h"
@interface FeedBackViewController()<UITextViewDelegate,UITextFieldDelegate,UIAlertViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    GCPlaceholderTextView  *userInput;
    UIView * userInputBgView;
    PromptInfoView * infoView;//提示信息
    UITextField * contactTextFeild;
    UILabel * statusLabel;
    UIButton * picBtn;
    UIActionSheet * picSheet;
    NSData * imageData;
    
    //多语言
    UILabel * titleNameLabel;
    UILabel * labelOne;
    UILabel * labelTwo;
    UILabel * labelThree;
    UIButton * btn;
    BOOL isUserInputChange;
    BOOL isEmilaChange;
    
    UIAlertView * alert;
}
@end

@implementation FeedBackViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom
        [self prepareUI];
         [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hiddenKeyboard) name:@"KCHiddenKeyBoardNotification" object:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = RGBA(237, 238, 241, 1);
    // Do any additional setup after loading the view.
    
    alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"feedBackAlterPromt", nil) message:NSLocalizedString(@"feedBackAlterMassage", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"alterSure", nil)  otherButtonTitles:nil];
    

    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    titleNameLabel.text = NSLocalizedString(@"feedBack", nil);
//    labelOne.text =  NSLocalizedString(@"yourFeedBack", nil);
//    labelTwo.text = NSLocalizedString(@"feedBackEmail", nil);
//    emilaTextField.placeholder = NSLocalizedString(@"feedBackChoose", nil);
//    statusLabel.text = [NSString stringWithFormat:@"250%@",NSLocalizedString(@"word", nil)];
//    [btn setTitle:NSLocalizedString(@"postFeedBack", nil) forState:UIControlStateNormal];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationItem.title=NSLocalizedString(@"feedBack", nil);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) prepareUI
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    self.view.backgroundColor = RGBA(237, 238, 241, 1);
    
    // 问题或建议
    
    // 必填图标
    UILabel * xingLabel = [[UILabel alloc]initWithFrame:CGRectMake(16, 18, 12, 12)];
    xingLabel.text = @"*";
    xingLabel.textColor = [UIColor redColor];
    [self.view addSubview:xingLabel];
    

    labelOne = [[UILabel alloc]initWithFrame:CGRectMake(28, 15, ScreenWidth-28, 16)];
//    labelOne.text =  NSLocalizedString(@"yourFeedBack", nil);
    labelOne.text = @"您遇到的问题或改进建议";
    labelOne.textColor = UIColorFromRGB(0x333333);
    labelOne.font = [UIFont systemFontOfSize:14.0];
    [self.view addSubview:labelOne];
    
    //userInput背景
    userInputBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 39, ScreenWidth, 160)];
    userInputBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:userInputBgView];
    
     //设置滚动条
    userInput =[[GCPlaceholderTextView  alloc] initWithFrame:CGRectMake(22, 0, ScreenWidth-44, 136)];
    userInput.font = [UIFont systemFontOfSize:15];
    userInput.textColor = UIColorFromRGB(0x333333);
    [userInput setScrollEnabled:YES];
    userInput.userInteractionEnabled = YES;
    userInput.editable = YES;
    userInput.showsVerticalScrollIndicator = YES;
    
//    userInput.placeholder = NSLocalizedString(@"feedBackPromt", nil);
    userInput.placeholder = @"问题描述或建议";
    userInput.placeholderColor = UIColorFromRGB(0xc1c1c1);
    
    userInput.keyboardType = UIKeyboardTypeDefault;
    userInput.returnKeyType = UIReturnKeyDefault;//返回键的类型
    userInput.scrollEnabled = YES;//是否可以拖动
    [userInputBgView addSubview:userInput];
    userInput.delegate = self;
    
    statusLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 136, ScreenWidth-16, 14)];
    statusLabel.backgroundColor = [UIColor whiteColor];
    statusLabel.font = [UIFont systemFontOfSize:12.0];
    statusLabel.text = [NSString stringWithFormat:@"250%@",NSLocalizedString(@"word", nil)];
    statusLabel.textAlignment = NSTextAlignmentRight;
    statusLabel.textColor = UIColorFromRGB(0xc1c1c1);
    [userInputBgView addSubview:statusLabel];
    
    
    // 添加照片
    labelTwo = [[UILabel alloc] initWithFrame:CGRectMake(16, 233-8-16, ScreenWidth-16, 16)];
    labelTwo.font = [UIFont systemFontOfSize:14];
    labelTwo.textColor = UIColorFromRGB(0x333333);
    labelTwo.text = @"添加照片";
    [self.view addSubview:labelTwo];
    
    UIView * picBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 233, ScreenWidth, 96)];
    picBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:picBgView];
    
    picBtn = [[UIButton alloc] initWithFrame:CGRectMake(22, 12, 72, 72)];
    [picBtn setBackgroundImage:[UIImage imageNamed:@"addpic_grey"] forState:UIControlStateNormal];
    [picBtn addTarget:self action:@selector(addPhoto) forControlEvents:UIControlEventTouchUpInside];
    [picBgView addSubview:picBtn];
    
    labelThree = [[UILabel alloc] initWithFrame:CGRectMake(16, 363-8-16, ScreenWidth-16, 16)];
    labelThree.text = @"您的联系方式";
    labelThree.textColor = UIColorFromRGB(0x333333);
    labelThree.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:labelThree];
    
    contactTextFeild = [[UITextField alloc] initWithFrame:CGRectMake(0, 363, ScreenWidth, 44)];
    contactTextFeild.backgroundColor = [UIColor whiteColor];
    contactTextFeild.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 22, 0)];
    contactTextFeild.leftViewMode = UITextFieldViewModeAlways;
    contactTextFeild.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"手机号码或邮箱" attributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0xc1c1c1),NSFontAttributeName:[UIFont systemFontOfSize:15]}];
    [self.view addSubview:contactTextFeild];
    
    //提交意见按钮
  
    UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    [button setTitle:NSLocalizedString(@"postFeedBack", nil) forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    [button setTitleColor:UIColorFromRGBAndA(0x7dc234, 1.0) forState:UIControlStateNormal];
    [button setTitleColor:UIColorFromRGBAndA(0x7dc234, 0.5) forState:UIControlStateDisabled];
    [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [button addTarget:self action:@selector(zoomInAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * saveBtn = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = saveBtn;
    saveBtn.enabled = NO;

    
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tapGr.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGr];
}

#pragma mark - 添加照片
- (void)addPhoto{
    [self getFromCameraOrPhoto];
}

- (void)getFromCameraOrPhoto{
    picSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"alterCancel",@"取消")destructiveButtonTitle:NSLocalizedString(@"takePhoto", @"拍照") otherButtonTitles:NSLocalizedString(@"getPhotoFromAlbum", @"从相册中选择") ,nil];
    [picSheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self getImageFromCamera];
    }
    else if (buttonIndex == 1)
    {
        [self getImageFromPhoto];
    }
}

#pragma mark ---拍照
-(void)getImageFromCamera
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = sourceType;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark --从相册中获取
-(void)getImageFromPhoto
{
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //pickerImage.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
        
    }
    pickerImage.delegate = self;
    pickerImage.allowsEditing = NO;
    [self presentViewController:pickerImage animated:YES completion:nil];
}

#pragma mark -- 选择照片或者照相完后触发的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage * image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    imageData = UIImageJPEGRepresentation(image, 0.5);
//    NSLog(@"",imageData.bytes);
    [picker dismissViewControllerAnimated:YES completion:nil];
    [picBtn setBackgroundImage:image forState:UIControlStateNormal];
}

-(void)viewTapped:(UITapGestureRecognizer *)tap
{
    [userInput resignFirstResponder];
    [contactTextFeild resignFirstResponder];
}

//提交意见按钮
-(void)zoomInAction:(id)sender {
    [userInput resignFirstResponder];
    [contactTextFeild resignFirstResponder];

    //提交意见到服务器
    if(userInput.text.length == 0)
    {
        [PromptInfoView showMessage:NSLocalizedString(@"feedBackNil", nil)];
    }else if(contactTextFeild.text.length!=0){
        if (![validateInputValue telePhoneValidate:contactTextFeild.text] && ![validateInputValue validateEmail:contactTextFeild.text]) {
            [PromptInfoView showMessage:@"联系方式格式有误" superView:self.view];
        }else{
            [self feedBackAdvise];
        }
    }else{
        [self feedBackAdvise];
    }
    
}

//提交意见
-(void)feedBackAdvise
{
//    NSMutableDictionary * dict = [[NSMutableDictionary alloc]init];
    //获得用户信息
//    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
//    NSString * uid = [userInfo objectForKey:@"uid"];
//    NSString * token = [userInfo objectForKey:@"token"];
//    [dict setValue:uid forKey:@"id"];
//    [dict setValue:userInput.text forKey:@"feedback"];
//    [dict setValue:token forKey:@"token"];
//    [dict setValue:contactTextFeild.text forKey:@"contact"];
//    RequestNetWork * rnk = [[RequestNetWork alloc]init];
//    [rnk initWithPath:POST(POSTFEED) params:dict block:^(id downLoadData, id error) {
//        if ([downLoadData objectForKey:@"data"] != nil) {
//            [PromptInfoView showMessage:NSLocalizedString(@"feedBackSuccess", nil)];
//            [self.navigationController popViewControllerAnimated:YES];
//        }
//        else if (error != nil) {
//            [PromptInfoView showMessage:[error objectForKey:@"info"]];
//        }
//
//    }];
    
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:UID forKey:@"id"];
    [postDict setValue:TOKEN  forKey:@"token"];
    [postDict setValue:userInput.text forKey:@"feedback"];
    [postDict setValue:contactTextFeild.text forKey:@"contact"];
    [self startWaiting:nil color:nil addToView:self.view];
    AFHTTPRequestOperationManager *mgr=[AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [mgr POST:POST(POSTFEED) parameters:postDict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (imageData != nil) {
            
            [formData appendPartWithFileData:imageData name:@"file" fileName:@"photo.jpg" mimeType:@"image/jpg"];
        }
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self stopWaiting];
//        id data = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
//        NSLog(@"======%@",data);
        [PromptInfoView showMessage:NSLocalizedString(@"feedBackSuccess", nil)];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [PromptInfoView showMessage:error];
    }];

}

-(void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length!=0){
        isUserInputChange = YES;
    }else{
        isUserInputChange = NO;
    }
    [self isChangeSendStatus];
    
    NSInteger number = [textView.text length];
    if (number > 250)
        
    {
        
        [alert show];
        userInput.text = [textView.text substringToIndex:250];
        number = 250;
        
    }
    NSString * firstString = NSLocalizedString(@"wordPromt", nil);
    NSString * secondString = NSLocalizedString(@"word", nil);
    statusLabel.text = [NSString stringWithFormat:@"%@%d%@",firstString,250-(int)number,secondString];
}


- (void)isChangeSendStatus{
    if (isUserInputChange) {
        self.navigationItem.rightBarButtonItem.enabled = YES;
    }else{
        self.navigationItem.rightBarButtonItem.enabled = NO;
    }
}


#pragma mark ==== uitextFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - 200, self.view.frame.size.width, self.view.frame.size.height);
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y + 200, self.view.frame.size.width, self.view.frame.size.height);
}

-(void)hiddenKeyboard
{
    [userInput resignFirstResponder];
    [contactTextFeild resignFirstResponder];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}




@end
